{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "45df4c52",
   "metadata": {},
   "source": [
    "## 知识概念\n",
    "\n",
    "\n",
    "> 1. 一切都是I/O：软工到产品的一般化知识\n",
    "> 1. 语音识别:speech recognition\n",
    "> 1. 语音唤醒\n",
    "> 1. 自动语音识别:Automatic Speech Recognition, 简称<font color=red> ASR </font>\n",
    ">> 1. 其目标是以电脑自动将人类的语音内容转换为相应的文字。与说话人识别及说话人确认不同，后者尝试识别或确认发出语音的说话人而非其中所包含的词汇内容。\n",
    "> 1. 语音合成:text to speech,简称<font color=red> TTS </font>\n",
    ">> 1. 将文字转化为语音的一种技术，类似于人类的嘴巴，通过不同的音色说出想表达的内容。 在语音合成技术中，主要分为 语言分析部分 和 声学系统部分 ，也称为 前端部分 和 后端部分， 语言分析部分主要是根据输入的文字信息进行分析，生成对应的语言学规格书，想好该怎么读；声学系统部分主要是根据语音分析部分提供的语音学规格书，生成对应的音频，实现发声的功能。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9684509",
   "metadata": {},
   "source": [
    "# 语音识别测试-百度API-ASR"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "26478ff1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "API_KEY = 'Zk0vqYYlnLUsAKrT0uvLKsab'\n",
    "SECRET_KEY = 'fcrMEHuiIUkHp2tdXDaDnBjH5GX34gpI'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6f69c7d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.dddc31f88f8df9c033e4c61dd78fd16c.315360000.1971866581.282335-25954563\",\"expires_in\":2592000,\"session_key\":\"9mzdDtaLJkyO1FhRisYGW9F7OKfiZCrklB5n7WDs9YZIrMMDnptFkrsD65TsKUGbpgm51d+ROsj25v6t++tnZ+clTllpow==\",\"access_token\":\"24.5d80be131c469b7a6aeee92b917da5fa.2592000.1659098581.282335-25954563\",\"scope\":\"public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_\\u53f0\\u6e7e\\u901a\\u884c\\u8bc1 vis-ocr_\\u6e2f\\u6fb3\\u901a\\u884c\\u8bc1 vis-ocr_\\u673a\\u52a8\\u8f66\\u8d2d\\u8f66\\u53d1\\u7968\\u8bc6\\u522b vis-ocr_\\u673a\\u52a8\\u8f66\\u68c0\\u9a8c\\u5408\\u683c\\u8bc1\\u8bc6\\u522b vis-ocr_\\u8f66\\u8f86vin\\u7801\\u8bc6\\u522b vis-ocr_\\u5b9a\\u989d\\u53d1\\u7968\\u8bc6\\u522b vis-ocr_\\u4fdd\\u5355\\u8bc6\\u522b vis-ocr_\\u673a\\u6253\\u53d1\\u7968\\u8bc6\\u522b vis-ocr_\\u884c\\u7a0b\\u5355\\u8bc6\\u522b brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"29d221324336004a36deec22be230d15\"}\n",
      "\n",
      "{'refresh_token': '25.dddc31f88f8df9c033e4c61dd78fd16c.315360000.1971866581.282335-25954563', 'expires_in': 2592000, 'session_key': '9mzdDtaLJkyO1FhRisYGW9F7OKfiZCrklB5n7WDs9YZIrMMDnptFkrsD65TsKUGbpgm51d+ROsj25v6t++tnZ+clTllpow==', 'access_token': '24.5d80be131c469b7a6aeee92b917da5fa.2592000.1659098581.282335-25954563', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '29d221324336004a36deec22be230d15'}\n"
     ]
    },
    {
     "ename": "DemoError",
     "evalue": "scope is not correct",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mDemoError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[1;32mIn [9]\u001b[0m, in \u001b[0;36m<cell line: 88>\u001b[1;34m()\u001b[0m\n\u001b[0;32m     86\u001b[0m \u001b[38;5;124;03m\"\"\"  TOKEN end \"\"\"\u001b[39;00m\n\u001b[0;32m     88\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;18m__name__\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124m__main__\u001b[39m\u001b[38;5;124m'\u001b[39m:\n\u001b[1;32m---> 89\u001b[0m     token \u001b[38;5;241m=\u001b[39m \u001b[43mfetch_token\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m     91\u001b[0m     \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m     92\u001b[0m \u001b[38;5;124;03m    httpHandler = urllib2.HTTPHandler(debuglevel=1)\u001b[39;00m\n\u001b[0;32m     93\u001b[0m \u001b[38;5;124;03m    opener = urllib2.build_opener(httpHandler)\u001b[39;00m\n\u001b[0;32m     94\u001b[0m \u001b[38;5;124;03m    urllib2.install_opener(opener)\u001b[39;00m\n\u001b[0;32m     95\u001b[0m \u001b[38;5;124;03m    \"\"\"\u001b[39;00m\n\u001b[0;32m     96\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21masr\u001b[39m(token,AUDIO_FILE):\n",
      "Input \u001b[1;32mIn [9]\u001b[0m, in \u001b[0;36mfetch_token\u001b[1;34m()\u001b[0m\n\u001b[0;32m     77\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m (\u001b[38;5;124m'\u001b[39m\u001b[38;5;124maccess_token\u001b[39m\u001b[38;5;124m'\u001b[39m \u001b[38;5;129;01min\u001b[39;00m result\u001b[38;5;241m.\u001b[39mkeys() \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mscope\u001b[39m\u001b[38;5;124m'\u001b[39m \u001b[38;5;129;01min\u001b[39;00m result\u001b[38;5;241m.\u001b[39mkeys()):\n\u001b[0;32m     78\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m SCOPE \u001b[38;5;129;01mand\u001b[39;00m (\u001b[38;5;129;01mnot\u001b[39;00m SCOPE \u001b[38;5;129;01min\u001b[39;00m result[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mscope\u001b[39m\u001b[38;5;124m'\u001b[39m]\u001b[38;5;241m.\u001b[39msplit(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m \u001b[39m\u001b[38;5;124m'\u001b[39m)):  \u001b[38;5;66;03m# SCOPE = False 忽略检查\u001b[39;00m\n\u001b[1;32m---> 79\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m DemoError(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mscope is not correct\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[0;32m     80\u001b[0m     \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mSUCCESS WITH TOKEN: \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m ; EXPIRES IN SECONDS: \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m'\u001b[39m \u001b[38;5;241m%\u001b[39m (result[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124maccess_token\u001b[39m\u001b[38;5;124m'\u001b[39m], result[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mexpires_in\u001b[39m\u001b[38;5;124m'\u001b[39m]))\n\u001b[0;32m     81\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m result[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124maccess_token\u001b[39m\u001b[38;5;124m'\u001b[39m]\n",
      "\u001b[1;31mDemoError\u001b[0m: scope is not correct"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = './audio/16k.pcm'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "\n",
    "\n",
    "# 极速版\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    \"\"\"\n",
    "    httpHandler = urllib2.HTTPHandler(debuglevel=1)\n",
    "    opener = urllib2.build_opener(httpHandler)\n",
    "    urllib2.install_opener(opener)\n",
    "    \"\"\"\n",
    "def asr(token,AUDIO_FILE):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    #测试自训练平台需要打开以下信息\n",
    "    #params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "    params_query = urlencode(params);\n",
    "\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "    print(\"url is\", url);\n",
    "    print(\"header is\", headers)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "f9da2a10",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 语音识别执行如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "ddea3018",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "fetch_token() takes 0 positional arguments but 2 were given",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[1;32mIn [11]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m token \u001b[38;5;241m=\u001b[39m \u001b[43mfetch_token\u001b[49m\u001b[43m(\u001b[49m\u001b[43mAPI_KEY\u001b[49m\u001b[43m,\u001b[49m\u001b[43mSECRET_KEY\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m      2\u001b[0m token\n",
      "\u001b[1;31mTypeError\u001b[0m: fetch_token() takes 0 positional arguments but 2 were given"
     ]
    }
   ],
   "source": [
    "token = fetch_token(API_KEY,SECRET_KEY)\n",
    "token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "55288d59",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'xu_token' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[1;32mIn [12]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m asr(\u001b[43mxu_token\u001b[49m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124maudio/16k.wav\u001b[39m\u001b[38;5;124m'\u001b[39m)\n",
      "\u001b[1;31mNameError\u001b[0m: name 'xu_token' is not defined"
     ]
    }
   ],
   "source": [
    "asr(xu_token,'audio/16k.wav')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3357f295",
   "metadata": {},
   "source": [
    "# 语音识别自动回复文本机器人\n",
    "\n",
    "> 1. 准备录制音频文件 （完成）\n",
    "> 2. 调用语音识别，将音频转成文本 （已完成）\n",
    "> 3. 文本自动回复 （已完成）原理: 问和答，I/O 输入和输出----特点： key:value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3066f384",
   "metadata": {},
   "source": [
    "## 准备录制音频文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4da27d3f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Collecting SpeechRecognition\n",
      "  Downloading SpeechRecognition-3.8.1-py2.py3-none-any.whl (32.8 MB)\n",
      "Installing collected packages: SpeechRecognition\n",
      "Successfully installed SpeechRecognition-3.8.1\n"
     ]
    }
   ],
   "source": [
    "!pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eda81044",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Collecting PyAudio\n",
      "  Downloading PyAudio-0.2.11.tar.gz (37 kB)\n",
      "Building wheels for collected packages: PyAudio\n",
      "  Building wheel for PyAudio (setup.py): started\n",
      "  Building wheel for PyAudio (setup.py): finished with status 'error'\n",
      "  Running setup.py clean for PyAudio\n",
      "Failed to build PyAudio\n",
      "Installing collected packages: PyAudio\n",
      "    Running setup.py install for PyAudio: started\n",
      "    Running setup.py install for PyAudio: finished with status 'error'\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  ERROR: Command errored out with exit status 1:\n",
      "   command: 'C:\\ProgramData\\Anaconda3\\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\86181\\\\AppData\\\\Local\\\\Temp\\\\pip-install-v8l8hvxs\\\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\86181\\\\AppData\\\\Local\\\\Temp\\\\pip-install-v8l8hvxs\\\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\\setup.py'\"'\"';f = getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__) if os.path.exists(__file__) else io.StringIO('\"'\"'from setuptools import setup; setup()'\"'\"');code = f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' bdist_wheel -d 'C:\\Users\\86181\\AppData\\Local\\Temp\\pip-wheel-rllucrd2'\n",
      "       cwd: C:\\Users\\86181\\AppData\\Local\\Temp\\pip-install-v8l8hvxs\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\n",
      "  Complete output (9 lines):\n",
      "  running bdist_wheel\n",
      "  running build\n",
      "  running build_py\n",
      "  creating build\n",
      "  creating build\\lib.win-amd64-3.9\n",
      "  copying src\\pyaudio.py -> build\\lib.win-amd64-3.9\n",
      "  running build_ext\n",
      "  building '_portaudio' extension\n",
      "  error: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n",
      "  ----------------------------------------\n",
      "  ERROR: Failed building wheel for PyAudio\n",
      "    ERROR: Command errored out with exit status 1:\n",
      "     command: 'C:\\ProgramData\\Anaconda3\\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\86181\\\\AppData\\\\Local\\\\Temp\\\\pip-install-v8l8hvxs\\\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\86181\\\\AppData\\\\Local\\\\Temp\\\\pip-install-v8l8hvxs\\\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\\setup.py'\"'\"';f = getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__) if os.path.exists(__file__) else io.StringIO('\"'\"'from setuptools import setup; setup()'\"'\"');code = f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\86181\\AppData\\Local\\Temp\\pip-record-6qp3vqhk\\install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:\\Users\\86181\\AppData\\Roaming\\Python\\Python39\\Include\\PyAudio'\n",
      "         cwd: C:\\Users\\86181\\AppData\\Local\\Temp\\pip-install-v8l8hvxs\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\n",
      "    Complete output (11 lines):\n",
      "    running install\n",
      "    C:\\ProgramData\\Anaconda3\\lib\\site-packages\\setuptools\\command\\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n",
      "      warnings.warn(\n",
      "    running build\n",
      "    running build_py\n",
      "    creating build\n",
      "    creating build\\lib.win-amd64-3.9\n",
      "    copying src\\pyaudio.py -> build\\lib.win-amd64-3.9\n",
      "    running build_ext\n",
      "    building '_portaudio' extension\n",
      "    error: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n",
      "    ----------------------------------------\n",
      "ERROR: Command errored out with exit status 1: 'C:\\ProgramData\\Anaconda3\\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\86181\\\\AppData\\\\Local\\\\Temp\\\\pip-install-v8l8hvxs\\\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\86181\\\\AppData\\\\Local\\\\Temp\\\\pip-install-v8l8hvxs\\\\pyaudio_e1d0420da0204e2d930055c7c8887215\\\\setup.py'\"'\"';f = getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__) if os.path.exists(__file__) else io.StringIO('\"'\"'from setuptools import setup; setup()'\"'\"');code = f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\86181\\AppData\\Local\\Temp\\pip-record-6qp3vqhk\\install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:\\Users\\86181\\AppData\\Roaming\\Python\\Python39\\Include\\PyAudio' Check the logs for full command output.\n"
     ]
    }
   ],
   "source": [
    "!pip install PyAudio\n",
    "\n",
    "!pip install pipwin\n",
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "862f08f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3e3ceac",
   "metadata": {},
   "source": [
    "## 文本自动回复"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ec48c95",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa = {\n",
    "    \"你好\":\"你好呀，有什么事么？\",\n",
    "    \"你叫什么名字\":\"我是人见人爱，花见花开的大大度呀\",\n",
    "    \"你多大了\":\"这是很私密的问题，我今年18岁了。\",\n",
    "    \"苹果用英文怎么说\":\"apple\",\n",
    "    \"今天天气\":\"我这边墨迹天气显示，今天广州30度，晴\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "631cea9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa.get('你好')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c81830cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa.get('你叫什么名字')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76dc96e2",
   "metadata": {},
   "source": [
    "## 实践"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "8f99d1f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 1.744306\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'apple'"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. 录制音频文件\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "# 通过调用电脑的麦克风进行音频的获取\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2. 调用百度asr\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result = eval(asr(xu_token,\"1.wav\"))['result'][0][:-1]  # eval()---> str to dict\n",
    "# asr_result\n",
    "\n",
    "# 3. 文本自动回复\n",
    "qa.get(asr_result)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49885d53",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
